import React, { Suspense, Fragment, useEffect } from 'react'
import { Redirect, Route, withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import Cookies from 'js-cookie'
import { actionCreators as orderActionCreators } from '../../pages/order/store'
import Header from '../header'
import Nav from '../nav'
import AppRouter from '../../routes'
import Login from '../../pages/login'
import AppMenu from '../../components/menu'
import { actionCreators } from '../../store'
import { TOKEN_KEY } from '../../constants'
import './style.scss'

function Container(props) {
  const { isLogin, getOrderStatusMap, getUserInfo } = props

  useEffect(() => {
    if (isLogin && Cookies.get(TOKEN_KEY)) {
      getOrderStatusMap()
      getUserInfo()
    }
  }, [isLogin])

  return (
    <div className="container">
      <Route path="/login" component={Login}/>
      {isLogin
        ? (
          <Fragment>
            <AppMenu/>
            <div className="content">
              <Header/>
              <div className="page">
                <Nav/>
                <div className="page--content">
                  <Suspense fallback={<div>加载中...</div>}>
                    <AppRouter/>
                  </Suspense>
                </div>
              </div>
            </div>
          </Fragment>
        ) : (
          <Redirect to="/login"/>
        )}
    </div>
  )
}

export default connect(state => ({
  isLogin: state.getIn(['common', 'isLogin'])
}), dispatch => ({
  getOrderStatusMap() {
    dispatch(orderActionCreators.getOrderStatusMap())
  },
  getUserInfo() {
    dispatch(actionCreators.getLoginUser())
  }
}))(withRouter(Container))
